jQuery.noConflict();
(function($, PLUGIN_ID) {

    'use strict';

    var config = kintone.plugin.app.getConfig(PLUGIN_ID);
    if (!config) {return false;}
    var rowCount = Number(config['rowCount']) - 1;
    var relatedAppId = config['relatedAppId'];
    var balanceDate = config['balanceDate'];
    var subtable = {};
    var currency = {};
    var exchangeRate = {};
    var i;
    var j;
    for (i = 0; i < rowCount; i++) {
        subtable[i] = config['subtable' + i];
        currency[i] = config['currency' + i];
        exchangeRate[i] = config['exchangeRate' + i];
    }
    var createChange = 'app.record.create.change.';
    var editChange = 'app.record.edit.change.';
    var indexEditChange = 'app.record.index.edit.change.';

    // Get records of the matching condition in the related app, then get the correct exchangeRate.
    function postExchangeRate(x, event, balanceDateVal, currencyVal, exchangeRateCell) {
        var url = kintone.api.url('/k/v1/records', true);
        var body = {
            app: relatedAppId,
            query: 'startDate <= "' + balanceDateVal + '" and endDate >= "' +
             balanceDateVal + '" and currency = "' + currencyVal + '"'
        };
        kintone.api(url, 'GET', body, function(resp) {
            // success:
            var relatedRecords = resp.records;
            if (relatedRecords.length !== 0) {
                exchangeRateCell['value'] = relatedRecords[0]['exchangeRate']['value'];
            } else {
                exchangeRateCell['value'] = 0;
            }
            kintone.app.record.set(event);
        });
    }

    // When change the balanceDate or currency in the detail edit page or create page.
    function exchangeRateTableGetValue(x, thiscurrency) {
        kintone.events.on([createChange + balanceDate, createChange + thiscurrency,
            editChange + balanceDate, editChange + thiscurrency, indexEditChange + balanceDate,
            indexEditChange + thiscurrency], function(ev) {
            var record = ev.record;
            var balanceDateVal = record[balanceDate]['value'];
            var currencyVal;
            var exchangeRateCell;
            if (subtable[x] === '-----') {
                currencyVal = record[currency[x]]['value'];
                exchangeRateCell = record[exchangeRate[x]];
                postExchangeRate(x, ev, balanceDateVal, currencyVal, exchangeRateCell);
            } else if (record[subtable[x]]) {
                for (j = 0; j < record[subtable[x]]['value']['length']; j++) {
                    currencyVal = record[subtable[x]]['value'][j]['value'][currency[x]]['value'];
                    exchangeRateCell = record[subtable[x]]['value'][j]['value'][exchangeRate[x]];
                    postExchangeRate(x, ev, balanceDateVal, currencyVal, exchangeRateCell);
                }
            }
        });
    }

    // The exchangeRate should be disabled when in the detail edit page or create page.
    kintone.events.on(['app.record.edit.show', 'app.record.create.show'],
        function(event) {
            var appRecord = event.record;
            var thisExchangeRate;
            for (i = 0; i < rowCount; i++) {
                if (subtable[i] === '-----') {
                    thisExchangeRate = appRecord[exchangeRate[i]];
                    thisExchangeRate['disabled'] = true;
                } else if (appRecord[subtable[i]]) {
                    var subtableLength = appRecord[subtable[i]]['value']['length'];
                    for (j = 0; j < subtableLength; j++) {
                        thisExchangeRate = appRecord[subtable[i]]['value'][j]['value'][exchangeRate[i]];
                        thisExchangeRate['disabled'] = true;
                    }
                } else {
                    continue;
                }
            }
            // The exchangeRate should be disabled when add the line of the subtable.
            $('.edit-subtable-gaia').on('click', '.add-row-image-gaia', function() {
                var subtableTr = $(this).closest('.edit-subtable-gaia').find('tr');
                var tdCount = $(this).closest('.edit-subtable-gaia').find('th').length - 1;
                for (var t = 0; t < tdCount; t++) {
                    var disabledTd = subtableTr.eq(1).find('td').eq(t);
                    if (disabledTd.find('input').prop('disabled') === true) {
                        var trCount = subtableTr.length;
                        for (i = 1; i < trCount; i++) {
                            subtableTr.eq(i).find('td').eq(t).find('input').attr('disabled', true);
                        }
                    }
                }
            });

            for (i = 0; i < rowCount; i++) {
                exchangeRateTableGetValue(i, currency[i]);
            }
            return event;
        });

    // Get the exchangeRate value when change the currency value in the index edit page.
    function exchangeRateGetValue(x, thiscurrency, relatedRecords) {
        kintone.events.on([indexEditChange + thiscurrency], function(ev) {
            var record = ev.record;
            var currencyVal;
            if (subtable[x] === '-----') {
                currencyVal = record[currency[x]]['value'];
                for (j = 0; j < relatedRecords.length; j++) {
                    var relatedCurrency = relatedRecords[j]['currency']['value'];
                    if (relatedCurrency === currencyVal) {
                        record[exchangeRate[x]]['value'] = relatedRecords[j]['exchangeRate']['value'];
                        break;
                    } else {
                        record[exchangeRate[x]]['value'] = 0;
                    }
                }
            }
            return ev;
        });
    }

    // The exchangeRate and balanceDate should be disabled when edit a record in the index edit page.
    kintone.events.on('app.record.index.edit.show', function(editevent) {
        var appRecord = editevent.record;
        appRecord[balanceDate]['disabled'] = true;
        for (i = 0; i < rowCount; i++) {
            if (appRecord[currency[i]]) {
                appRecord[exchangeRate[i]]['disabled'] = true;
            }
        }
        // Get the records of the related table when edit a record in the index edit page.
        var balanceDateVal = appRecord[balanceDate]['value'];
        var url = kintone.api.url('/k/v1/records', true);
        var body = {
            app: relatedAppId,
            query: 'startDate <= "' + balanceDateVal + '" and endDate >= "' +
             balanceDateVal + '"'
        };
        kintone.api(url, 'GET', body, function(resp) {
            // success:
            var relatedRecords = resp.records;
            for (i = 0; i < rowCount; i++) {
                exchangeRateGetValue(i, currency[i], relatedRecords);
            }
        });
        return editevent;
    });

})(jQuery, kintone.$PLUGIN_ID);
